package jp.dev7.hongo2.worker;

import java.io.IOException;

import jp.dev7.android.util.AbstractDownloadWorker;
import jp.dev7.hongo2.Hongo2;
import jp.dev7.hongo2.entity.Question;
import jp.dev7.hongo2.proto.Hongo.QuestionListProto;
import jp.dev7.hongo2.proto.Hongo.QuestionProto;
import jp.dev7.hongo2.util.Db4oHelper;

import org.apache.http.HttpResponse;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;

public class DownloadWorker extends AbstractDownloadWorker<QuestionListProto> {

	private Context context;

	public DownloadWorker(Context context, ProgressBar progressBar) {
		super(progressBar, Hongo2.URL + "/download");
		this.context = context;
	}

	@Override
	protected QuestionListProto parseResponse(HttpResponse response)
			throws IOException {
		return QuestionListProto.parseFrom(response.getEntity().getContent());
	}

	@Override
	protected Message done(QuestionListProto list) {
		Message message = new Message();

		Db4oHelper db4o = new Db4oHelper(context);
		try {
			if (progressBar != null) {
				progressBar.setMax(list.getItemCount());
			}

			int progress = 0;
			for (QuestionProto qp : list.getItemList()) {

				Question q = new Question();
				q.key = qp.getKey();
				q.content = qp.getContent();
				q.selection0 = qp.getSelection0();
				q.selection1 = qp.getSelection1();
				q.selection2 = qp.getSelection2();
				q.selection3 = qp.getSelection3();

				db4o.saveQuestion(q);

				progress += 1;
				if (progressBar != null) {
					progressBar.setProgress(progress);
				}

				Log.d("hongo", "download = " + q);
			}

			db4o.commit();
		} catch (Exception e) {
			db4o.rollback();
		} finally {
			db4o.close();
		}

		Bundle bundle = new Bundle();
		bundle.putBoolean(RESULT, true);
		message.setData(bundle);
		return message;
	}

}
